// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
var NODE_PADDING = 100;
cc.Class({
    extends: cc.Component,

    properties: {
        coinPrefabs:cc.Prefab,
        boardFrame:cc.SpriteFrame,
        _coins : [],
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

    },

    start () {
        var levelsData = {};
        levelsData[0] = {}
        levelsData[0].rows = 4,
        levelsData[0].cols = 4,
        levelsData[0].grid = [
                [1, 1, 1, 1],
                [1, 1, 0, 1],
                [1, 0, 0, 0],
                [1, 1, 0, 1]
            ]
        this.initBoard(levelsData[0]);
    },

    update (dt) {

    },
    initBoard:function(levelData){
        var self = this;
        self.gird = levelData.grid;
        self.rows = levelData.rows;
        self.cols = levelData.cols;
        self._coins = [];
        self.flipAnimationCount = 0;

        var offsetX = -Math.floor(NODE_PADDING*self.cols/2) + NODE_PADDING/2;
        var offsetY = -Math.floor(NODE_PADDING*self.rows/2) + NODE_PADDING/2;
        for (let i = 0; i < self.rows; i++) {
            var y = i*NODE_PADDING+offsetY;
            for (let j = 0; j < self.cols; j++) {
                var x = j*NODE_PADDING + offsetX;
                //创建硬币背景
                var coinbg = new cc.Node();
                var sp = coinbg.addComponent(cc.Sprite);
                sp.spriteFrame = self.boardFrame;
                coinbg.parent = self.node;
                coinbg.position = cc.v2(x,y);

                //创建硬币
                var nodeType = self.gird[i][j];
                if(nodeType != "X"){
                    var coin = cc.instantiate(self.coinPrefabs);
                    coin.parent = self.node;
                    coin.position = cc.v2(x,y);
                    coin.row = i;
                    coin.col = j;
                    coin.getComponent('coin').createNewCoin(nodeType);
                    self._coins.push(coin);
                    self.gird[i][j] = coin;
                }
            }       
        }
        self.node.on("touchstart",self.touchStart,this);
    },
    //触摸控制
    touchStart:function(event){
        if (this.flipAnimationCount > 0)  return 

        var pos = this.node.convertToNodeSpaceAR(event.getLocation());
        var padding = NODE_PADDING/2;
        for (let i = 0; i < this._coins.length; i++) {
            const element = this._coins[i];
            var cx = element.x;
            var cy = element.y;
            if(pos.x>=cx-padding && pos.x <= cx+padding && pos.y >=cy-padding && pos.y<=cy+padding){
                this.flipCoin(element,true);
            }
        }
    },
    //获取硬币
    getCoin:function(row,col){
        if(this.gird[row]){
            return this.gird[row][col];
        }
    },
    //检查是否完成
    checkLevelCompleted:function(){
        var count = 0;
        for (let i = 0; i < this._coins.length; i++) {
            const element = this._coins[i];
            if(element.getComponent('coin').getIsWhite()){
                count += 1;
            }
        }
        if(count == this._coins.length){
            //完成本局
            this.node.off("touchstart");
        }
    },
    //翻转硬币
    flipCoin:function(coin,includeNeighbour){
        var self = this;
        if(!coin || coin == "X"){
            return;
        }
        self.flipAnimationCount += 1;
        coin.getComponent('coin').flipCoin(()=>{
            self.flipAnimationCount -=1;
            if(self.flipAnimationCount == 0){
                self.checkLevelCompleted();
            }
        });
        if(includeNeighbour){
            //播放音乐
            this.node.runAction(cc.sequence(cc.delayTime(0.25),cc.callFunc(()=>{
                self.flipCoin(self.getCoin(coin.row-1,coin.col),false);
                self.flipCoin(self.getCoin(coin.row+1,coin.col),false);
                self.flipCoin(self.getCoin(coin.row,coin.col-1),false);
                self.flipCoin(self.getCoin(coin.row,coin.col+1),false);

            },this)));
        }
    },

});
